package im.agents.service;

import im.agents.IMAgent;
import im.agents.migration.BestLocationRequester;
import im.domain.SLA;
import im.domain.XMLSerializer;
import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPANames;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

public class HandleViolations extends CyclicBehaviour {

	private SLA sla;
	public HandleViolations(Agent a, SLA sla){
		super(a);
		this.sla=sla;
	}
	@Override
	public void action() {
		ACLMessage msg = myAgent.receive(MessageTemplate.and(
				MessageTemplate.MatchContent("violazione"),
				MessageTemplate.MatchPerformative(ACLMessage.INFORM)));
		if(msg!=null){
			
			System.out.println(myAgent.getLocalName()
					+ " - Segnalata violazione SLA: "+sla.toString()+" quindi provo a migrare");
			DFAgentDescription[] ds = findMigrationManager();
    		if(ds== null||ds.length<=0){
    			System.out.println("MigrationManager not found");
    		}else {
    			ACLMessage request = new ACLMessage(ACLMessage.REQUEST);
    			request.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);
    			request.setSender(myAgent.getAID());
    			request.setContent(XMLSerializer.doSerialize(((IMAgent)myAgent).getTHRESHOLD()));
    			request.addReceiver(ds[0].getName());
    			BestLocationRequester bestLocationRequester = new BestLocationRequester(myAgent,request);
    			myAgent.addBehaviour(bestLocationRequester);
    		}
			
		}else{
			block();
		}
	}
	
	private DFAgentDescription[] findMigrationManager() {
		DFAgentDescription[] ds = null;
		try {
			DFAgentDescription dfd = new DFAgentDescription();
			ServiceDescription s = new ServiceDescription ();
			s.setName("migration-manager");
			s.setType("migration-manager");
			dfd.addServices(s);
			ds = DFService.search(myAgent, dfd);
			
		} catch (FIPAException e) {
			e.printStackTrace();
			return null;
		}
		return ds;
	}

}
